"""
    B/S Web服务端
"""

from socket import *
from select import select

class Handle:
    def __init__(self,html):
        self.html = html

    def handle(self,connfd,rlist):
        data = connfd.recv(1024 * 1024)
        print(data.decode())
        if not data:
            connfd.close()
            rlist.remove(connfd)
            return
        # 解析请求
        info = data.decode().split(" ")[1]
        print("请求内容",info)
        if info == "/":
            info = "/index.html"
            self.__response(connfd,info)
        else:
            try:
                file = open(self.html+info,"rb")
                print("图片：",self.html+info)
            except:
                info = "/404.html"
                self.__response(connfd,info)
                return
            self.__response(connfd,info)


    def __response(self,connfd,info):
        file = open(self.html+info,"rb")
        data = file.read()
        # 组织响应
        response = "HTTP 200 OK\r\n"
        response += "Content-Type:text/html\r\n"
        response += "\r\n"
        response = response.encode() + data
        #发送响应
        connfd.send(response)


class WebServer:
    def __init__(self,*,host="",port=0,html=None):
        self.host = host
        self.port = port
        self.address = (host,port)
        self.html = html
        self.sock = self._create_socket()
        self.rlist = []
        self.handle = Handle(html)

    def start(self):
        self.sock.listen(5)
        self.sock.setblocking(False)
        self.rlist.append(self.sock)
        while True:
            rs,_,_ = select(self.rlist,[],[])
            for r in rs:
                if r is self.sock:
                    self.__connect(r)
                else:
                    try:
                        self.handle.handle(r,self.rlist)
                        self.rlist.remove(r)
                        r.close()
                    except:
                        break

    def _create_socket(self):
        tcp_socket = socket()
        tcp_socket.bind(self.address)
        return tcp_socket

    def __connect(self, sock):
        connfd, addr = sock.accept()
        print(f"Connect from {addr}")
        connfd.setblocking(False)
        self.rlist.append(connfd)


if __name__ == '__main__':
    httpserver = WebServer(host="0.0.0.0",port=1119,html="./static")
    httpserver.start()
